package com.jp.fm.service;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.apache.commons.lang3.StringUtils;

import com.jp.fm.HomeFinanceRunner.ReverseFloatComparator;
import com.jp.fm.dao.CategoryDao;
import com.jp.fm.dao.TransactionDao;
import com.jp.fm.data.Category;
import com.jp.fm.data.Transaction;

public class CategoryService {

	private TransactionService transactionService = null;
	private TransactionDao transactionDao = null;
	private CategoryDao categoryDao = null;

	public Map<Float, Category> getTopCategoriesOverTimeFrame(
			final Date startDate, final Date endDate) {

		// Get the top categories
		Map<Float, Category> topCatMap = new TreeMap<Float, Category>(
				new ReverseFloatComparator());

		Set<Category> cats = categoryDao.findAll();

		for (Category category : cats) {

			// Top categories this month
			List<Transaction> trans = transactionDao.findByAny(category,
					startDate, endDate, null, null, null);

			Float topCatAmount = transactionService.calculateTransactionsTotal(
					trans, category);

			if (topCatAmount > 0) {
				topCatMap.put(topCatAmount, category);
			}
		}

		return topCatMap;
	}

	public Integer getCategoryByKeyword(final String str) {

		Integer categoryId = null;

		Map<String, String> keywordMap = categoryDao
				.findAllKeywordToCategoryMappings();
		Set<String> keys = keywordMap.keySet();
		for (Iterator<String> iterator = keys.iterator(); iterator.hasNext();) {
			String key = iterator.next();

			if (StringUtils.containsIgnoreCase(new StringBuffer(str),
					new StringBuffer(key))) {
				categoryId = categoryDao.findByName(keywordMap.get(key))
						.getId();
				break;
			}

		}

		if (null == categoryId) {
			categoryId = categoryDao.findByName("Unknown").getId();
		}

		return categoryId;
	}

	public final void setTransactionService(
			final TransactionService transactionService) {
		this.transactionService = transactionService;
	}

	public final void setTransactionDao(final TransactionDao transactionDao) {
		this.transactionDao = transactionDao;
	}

	public final void setCategoryDao(final CategoryDao categoryDao) {
		this.categoryDao = categoryDao;
	}
}
